# -*- coding: utf-8 -*-
from music.play import playMusic # pip install pygame
import requests  # 导入requests
import random  # 取随机数
import time
import urllib3
from lxml import etree
from config.conf import proxiesDEF, Referer_list
from config.useragent import user_agent_list
from method.readCheckAsin import readCheckAsinTxt
from method.readWhiteNameTxt import readWhiteNameTxt
from method.readInterimWhiteNameTxt import readInterimWhiteNameTxt
from method.sendEmail import SendEmail
from method.callPhone import SendCodeViewSet
import my_fake_useragent as ua
user_agent = ua.UserAgent()
get_goods_num = 0
goodsArr = []
user_agent_len = len(user_agent_list) - 10
Referer_list_len = len(Referer_list) - 1
whiteNameArr = readWhiteNameTxt()
checkAsinArr = readCheckAsinTxt()
InterimWhiteNameArr = readInterimWhiteNameTxt()
whiteNameArr.extend(InterimWhiteNameArr)
print('需要检查的 Asin--------------------')
print(checkAsinArr)
print('临时白名单 ------------------------')
print(InterimWhiteNameArr)
print('白名单（包含临时白名单） ------------')
print(whiteNameArr)


def getAsin():
    proxies_list = ['140.143.48.49:1080', '125.65.79.60:3311', '58.17.125.215:53281', '39.108.71.144:8000', '61.178.149.237:59042', '47.106.197.184:8000', '122.152.138.139:80', '112.250.107.37:53281', '106.104.12.180:80', '123.206.54.52:8118', '60.211.218.78:53281', '58.211.134.98:38480', '218.108.175.15:80', '1.34.146.163:30086', '119.178.101.18:8888', '192.144.191.242:80', '124.172.232.49:8010', '119.23.221.40:8118', '221.226.94.218:110', '27.191.234.69:9999', '139.199.19.174:8118', '120.79.64.147:8118', '59.172.27.6:38380', '61.160.210.223:808', '61.160.210.234:808', '47.95.249.140:8118']
    # boo = [True, False, True, False, False, False, False, False]
    # boo = [True]
    # try:
    #     if random.choice(boo):
    #         proxies_list = proxiesDEF()
    #         print(proxies_list)
    # except:
    #     print('获取ip失败')
    checkfollowSeller(checkAsinArr, proxies_list)


def checkfollowSeller(checkAsinArr, proxies_list):
    global get_goods_num
    for index, goods in enumerate(checkAsinArr):
        print('==%s============%s===========================%s======' % (goods, index, get_goods_num))
        url = 'https://www.amazon.com/gp/offer-listing/%s' % goods
        print(url)
        proxies = {'http': proxies_list[random.randint(0, len(proxies_list)-1)]}
        headers = {
            'User-Agent': user_agent.random(),
            # 'User-Agent': user_agent_list[random.randint(0, user_agent_len)],
            # 'Referer': Referer_list[random.randint(0, Referer_list_len)]
        }

        followArr = []
        try:
            urllib3.disable_warnings()
            session = requests.session()
            cookie = {'session-id': '133-6601898-5690606', 'ubid-main': '134-2195699-6860430',
                      'x-wl-uid': '1sO46Mqh6SKcW+BjRAZ+E++yhRBvTn/pdnYF0xjOL3vEQKiN+PD30aEKDFVDN/cUVNgVbmn1nL80=',
                      'session-token': 'inSc2Q4/90BYSrv1likZycKCgrWGuc08mRej5dgnjB/Ma5uau/XezdiGu7MvWlnB2Db8MP4/D9tvusAYUHgVJMm3bD5NWVCvI94dvia2WGOHzW8zyYktrv/mOQg7uqlbHwFRaBSNFHb2sqNDCknsHQHzHD7JKjkUwszMUpAKUYP8tlrGlMq4gzCKWgsISR08FBIZJ4eguFKckt06ruz+V1mUYZGAfc7klUu6WYdn5GbjM8TVWrI4T1HrJsScqWQ8RlFwJiAviK0=',
                      'session-id-time': '2082787201l'}
            print(proxies)
            response = session.get(url, headers=headers, proxies=proxies, verify=False, cookies=cookie, timeout=(3, 7))

            with open('ooo.html', 'w', encoding="utf-8") as fp:
                fp.write(response.content.decode('utf-8'))

            response_soup = etree.HTML(response.content.decode('utf-8'))
            time.sleep(random.uniform(3.5, 5.3))
            try:
                resList = response_soup.xpath('//*[@id="olpOfferList"]/div/div/div[@class="a-row a-spacing-mini olpOffer"]')
                print(len(resList))
                for list in resList:
                    sellerID = list.xpath('.//div[4]/h3/span/a/@href')[0].strip().split('seller=')[1]
                    followArr.append(sellerID)
                print('在 卖的seller数组 ===================%s' % followArr)
                # print('在 %s  卖的seller数组 ===================%s' % goods % followArr)
                # followArr  获取到跟点的商家
                for follow in followArr:
                    isWhite = False
                    # 我们设置的 whiteNameArr 白名单商家
                    for white in whiteNameArr:
                        if follow == white:
                            isWhite = True
                    if not isWhite:
                        print('这是跟卖你的点 follow seller====   %s' % follow)
                        # 检测的点 asin     跟卖你的点 followAsin
                        SendEmail().send_email(goods, follow)
                        print(115)
                        SendCodeViewSet().post('13622327097')
                        print(116)
                        playMusic('./music/TheCross.mp3', 2, 0.0)
                        print(117)

                    else:
                        print('%s === 这个是白名单的 seller  ' % follow)

            except:
                print('resList err')
                getAsin()
            # 清空followArr
            # print('清空followArr empty followArr')
            del followArr[:]
        except Exception as exc:
            print(exc)
            print('get 请求失败 从新走一遍')
            getAsin()
    print('检查完一遍=====****10分钟后开始巡查=*******************************************************====================================')
    # time.sleep(random.uniform(5.1, 5.3))
    time.sleep(random.uniform(613.5, 615.3))
    get_goods_num = get_goods_num + 1
    getAsin()


if __name__ == '__main__':
    getAsin()




